/*
 * Copyright (C) 2017 Honeywell, Inc. All Rights Reserved.
 */

package org.thanos.demo.redisson.util;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

public class DistributedLock implements AutoCloseable {

    private static final Logger log = LoggerFactory.getLogger(DistributedLock.class);

    private RedissonClient redissonClient;
    private RLock lock = null;
    private String lockKey;
    private Integer waitTimeout;
    private Integer lockTimeout;

    public DistributedLock(String lockKey, RedissonClient redissonClient) throws InterruptedException {
        this.lockKey = lockKey;
        this.redissonClient = redissonClient;
        this.waitTimeout = 10;
        this.lockTimeout = 10;
        this.acquire();
    }

    public DistributedLock(String lockKey, RedissonClient redissonClient, Integer waitTimeout, Integer lockTimeout) throws InterruptedException {
        this.lockKey = lockKey;
        this.redissonClient = redissonClient;
        this.waitTimeout = waitTimeout;
        this.lockTimeout = lockTimeout;
        this.acquire();
    }

    private void acquire() throws InterruptedException {
        this.lock = this.redissonClient.getLock(this.lockKey);
        if (!this.lock.tryLock(this.waitTimeout, this.lockTimeout, TimeUnit.SECONDS)) {
            log.error("acquire redisson lock failed.");
            throw new InterruptedException();
        }
    }

    private void release() {
        if (Objects.nonNull(this.lock)) {
            this.lock.unlock();
        }
    }

    @Override
    public void close() throws Exception {
        this.release();
    }
}
